package com.ptswitch.material.service.impl;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.Hibernate;
import org.hxzon.project.AbstractModelService;
import org.hxzon.util.BitUtil;
import org.hxzon.util.StringUtil;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.service.ContractService;

@Service
public class ContractServiceImpl extends AbstractModelService<Contract> implements ContractService {

    public Contract findById(String id, int init) {
        Contract contract = dao.findById(Contract.class, id);
        if (contract != null) {
            if (BitUtil.isSet(init, Init_Items)) {
                Hibernate.initialize(contract.getContractItems());
            }
            if (BitUtil.isSet(init, Init_Payments)) {
                Hibernate.initialize(contract.getContractPayments());
            }
            if (BitUtil.isSet(init, Init_Invoices)) {
                Hibernate.initialize(contract.getContractInvoices());
            }
            if (BitUtil.isSet(init, Init_Uploads)) {
                Hibernate.initialize(contract.getAttachments());
            }
        }
        return contract;
    }

    public List<Contract> findAllByContractStatus(String status, long first, long size) {
        return dao.findList(Contract.class, " where p.status='" + status + "'", first, size);
    }

    public List<Contract> findByVisitor(Uzer visitor, long first, long size) {
        String hql = " where p.status='" + Contract.Status_UnOk + "'";
        switch (visitor.getDepartment()) {
        case Uzer.Department_Buyer:
            hql += " and p.creater.id='" + visitor.getId() + "'";
            break;
        case Uzer.Department_Financial:
            hql += " and (p.numUnreplyPayment >0 or p.numUnreplyInvoice >0 ) and p.financial.id='" + visitor.getId() + "'";
            break;
        case Uzer.Department_Production:
            hql += " and (p.numUnpassAndUnexamine >0) and p.production.id='" + visitor.getId() + "'";
            break;
        case Uzer.Department_ContractAuditor:
            //FIXME
            hql = " where (p.status='" + Contract.Status_UnOk + "' or p.askDelete=true or p.askReset=true) ";
            hql += " and p.auditor.id='" + visitor.getId() + "'";
            break;
        }
        return dao.findList(Contract.class, hql, first, size);
    }

    public void save(Contract model) {
//		model.setCreateTime(DateUtil.formatToUniteTime(new Date()));
        dao.save(model);
    }

    private Pattern p = Pattern.compile(".*-\\d*-(\\d)");

    @SuppressWarnings("unchecked")
    public String emptyCode(String code) {
        code = StringUtil.escapeSql(code);
        List<String> list = (List<String>) dao.query("select p.code from Contract as p where p.code like '" + code + "-%' order by p.code", -1, -1);// code-%
        if (list.isEmpty()) {
            return code + "-1";
        }
        String lastCode = list.get(list.size() - 1);
        logger.debug("get empty code:{}", lastCode);
        Matcher m = p.matcher(lastCode);
        try {
            m.matches();
            int index = Integer.parseInt(m.group(1)) + 1;
            return code + "-" + index;
        } catch (RuntimeException e) {
            logger.error("get empty code fail", e);
        }
        return code;
    }

}
